package igor.mass.comm;

import java.io.IOException;
import java.util.HashMap;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import com.google.gson.Gson;

import android.R.string;
import android.util.Log;

public class CommunicationClient {
	public static String ip = "192.168.1.114";
	
	public String getStructure() {
    	String str = null;
    	String address = "http://"+ip+":8080/smarthouse/FetchStructure";

        try
    	{
    		HttpClient hc = new DefaultHttpClient();
    		HttpGet get = new HttpGet(address);

    		ResponseHandler<String> responseHandler=new BasicResponseHandler();
    		str = hc.execute(get, responseHandler);
    	}catch(IOException e){
    		e.printStackTrace();
    		Log.e("###", e.getMessage());
    		Log.e("###", e.getMessage());
    		Log.e("###", e.getMessage());
    	}  
    	
    	return str;
    }
	
	public String getInitialValues(int deviceId, int commandId) {
    	String str = null;
    	String url = "http://"+ip+":8080/smarthouse/FetchInitialValues?deviceId="+deviceId+"&commandId="+commandId;

        try
    	{
    		HttpClient hc = new DefaultHttpClient();
    		HttpGet get = new HttpGet(url);

    		ResponseHandler<String> responseHandler=new BasicResponseHandler();
    		str = hc.execute(get, responseHandler);

    	}catch(IOException e){
    		e.printStackTrace();
    		Log.e("###", e.getMessage());
    		Log.e("###", e.getMessage());
    		Log.e("###", e.getMessage());
    	}  
    	return str;
    }
	
	public String sendCommand(int deviceId, int commandId, HashMap<Integer, String> commandParamsValues){
    	String str=null;
		String url = "http://"+ip+":8080/smarthouse/SendCommand?deviceId="+deviceId+"&commandId="+commandId;

        try
    	{
    		HttpClient hc = new DefaultHttpClient();
    		//HttpGet get = new HttpGet(url);
    		HttpPost post = new HttpPost(url);

    		Gson gson = new Gson();
    		String outboundData = gson.toJson(commandParamsValues);
    		
    		StringEntity se = new StringEntity( "" + outboundData);  
            se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
            post.setEntity(se);
            
            
    		ResponseHandler<String> responseHandler=new BasicResponseHandler();
    		str = hc.execute(post, responseHandler);

    	}catch(IOException e){
    		e.printStackTrace();
    		Log.e("###", e.getMessage());
    		Log.e("###", e.getMessage());
    		Log.e("###", e.getMessage());
    	}  
        
        return str;
	}

}
